package me.ingxin.android.tools

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.telephony.TelephonyManager
import androidx.annotation.RequiresPermission

/**
 * Wifi是否已连接
 * @return true wifi打开，false非wifi
 */
@RequiresPermission(value = "android.permission.ACCESS_NETWORK_STATE")
fun isWifiConnected(context: Context): Boolean {
    val manager = try {
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
    } catch (ex: Exception) {
        ex.printStackTrace()
        null
    }
    return manager?.getNetworkCapabilities(manager.activeNetwork)
        ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
        ?: false
}

/**
 * 是否有网络连接
 */
@RequiresPermission(value = "android.permission.ACCESS_NETWORK_STATE")
fun isConnected(context: Context): Boolean {
    val manager = try {
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
    } catch (ex: Exception) {
        ex.printStackTrace()
        null
    }
    return manager?.getNetworkCapabilities(manager.activeNetwork)?.let {
        //wifi
        it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
                //流量
                || it.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
                //以太网
                || it.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
    } ?: false
}

/**
 * 获取运营商类型
 * @return -2-未知运营商，0-移动，1-联通，2-电信
 */
fun getSimOperator(context: Context): Int {
    val operator = try {
        val teleManager = context.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager
        teleManager?.simOperator
    } catch (ex: Exception) {
        ex.printStackTrace()
        return -2
    }
    return when {
        operator.isNullOrEmpty() -> -2

        //移动
        operator.startsWith("46000") || operator.startsWith("46002")
                || operator.startsWith("46004") || operator.startsWith("46007")
                || operator.startsWith("46008") -> 0

        //联通
        operator.startsWith("46001") || operator.startsWith("46006")
                || operator.startsWith("46009") || operator.startsWith("46010") -> 1

        //电信
        operator.startsWith("46003") || operator.startsWith("46005")
                || operator.startsWith("46011") || operator.startsWith("46012") -> 2

        else -> -2
    }
}